package qsou.rpc.framework.common.factory;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @auther: wuxw
 * @Date: 2022/3/29 15:39
 */
public class SingletonFactory {
  private static final Map<String,Object> OBJECT_MAP = new ConcurrentHashMap<>();

  private SingletonFactory(){

  }
  public static <T> T getInstance(Class<T> c){
    if(c == null){
      throw new IllegalArgumentException();
    }
    String key = c.toString();
    if(OBJECT_MAP.containsKey(key)){
      return c.cast(OBJECT_MAP.get(key));
    }else{
      return c.cast(OBJECT_MAP.computeIfAbsent(key , k-> {
        try {
          return c.getDeclaredConstructor().newInstance();
        } catch (InstantiationException e) {
          e.printStackTrace();
          throw new RuntimeException(e.getMessage(), e);
        } catch (IllegalAccessException e) {
          e.printStackTrace();
          throw new RuntimeException(e.getMessage(), e);
        } catch (InvocationTargetException e) {
          e.printStackTrace();
          throw new RuntimeException(e.getMessage(), e);
        } catch (NoSuchMethodException e) {
          e.printStackTrace();
          throw new RuntimeException(e.getMessage(), e);
        }
      }));
    }
  }

}